<?php
/**
 * 经纪人自动推送房源
 */

namespace app\crontab\controller\always;


use app\common\lib\RespCode;
use custom\Log;
use push\Aurora2;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class AgentAutoPush extends Command {

    protected function configure() {
        $this->setName('AgentAutoPush');
    }

    protected function execute(Input $input, Output $output) {
        $this->initial();
    }

    public function initial() {
        echo "starting\n";
        try {
            //需要处理的经纪人总数
            $count = db('agent_demand')
                ->field('agent_id')
//                ->where('agent_id',202)
                ->group('agent_id')
                ->count();
            if (empty($count)) throw new Exception("无需处理", RespCode::PARAMS_ERR);
            $long = 10;//一页处理10条
            $page = ceil($count / $long);//总页数
            for ($j = 1; $j <= $page; $j++) {
                //分页需要
                $list = db('agent_demand')
                    ->field('agent_id')
//                    ->where('agent_id',202)
                    ->group('agent_id')
                    ->page($j, $long)
                    ->column('agent_id');
                foreach ($list as $v) {
                    //处理需求
                    $res = self::mergeDemand($v);
                    //有匹配房源
                    if ($res['data']) {
                        $id_str = join(',', $res['data']);//房源id
                        $data = [
                            'title'           => '我们已为您推荐' . count($res['data']) . '套房源。点击查看',    //消息
                            'house'           => $id_str,   //房源id
                            'registration_id' => $res['registration_id'],//设备号
                            'agent_id'        => $res['agent_id'],//经纪人id
                            'is_read'         => 0,//未读
                            'itime'           => time(),//添加时间
                        ];
                        $cids = Aurora2::getCid($res['agent_id']);
                        //写message_agent_house表
                        if (!Db::name('message_agent_house')->insert($data)) {
                            throw new Exception('操作失败');
                        }
                        //registration_id不为空
                        if (!empty($res['registration_id'])) {
                            //推送
                            if (!Aurora2::push($cids[0], $res['registration_id'], $data['title'], Aurora2::TYPE1))
                                throw new Exception('推送失败' . $res['registration_id']);
                        }
                    }
                }
            }
            echo "end\n";
        } catch (Exception $e) {
            Db::close();
            $err = $e->getMessage() . ' (' . $e->getCode() . '), ' . $e->getFile() . ' (' . $e->getLine() . ')' . "\n" . $e->getTraceAsString() . "\r\n\r\n";
            Log::write($err, "AgentAutoPushErr.log");
        }
    }

    /**
     * 按经纪人需求匹配房源
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function mergeDemand($agentId) {
        //多个需求
        $agent_demand = db('agent_demand')
            ->where('agent_id', $agentId)
            ->select();
        //设备号
        $registration_id = db('company_agent')
                ->where('id', $agentId)
                ->value('registration_id') ?? '';
        $merge = [];
        foreach ($agent_demand as $v) {
            $map = [];
            $map[] = ['h.is_shelf', '=', 1];//上架
            $map[] = ['h.deleted', '=', 0];//未删除
            $map[] = ['ha.auction_status', 'in', [1, 2]];//待开始、进行中
            //区域
            if ($v['type'] == 1) {//不限
                if (empty($v['area_code'])) {
                    $p_codes = Db::name('region')->where('city_code', $v['city_code'])->value('p_codes');
                    $codes = $p_codes . $v['city_code'] . ',';
                    $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
                } else {
                    $map[] = ['h.city_code', 'in', $v['area_code']];
                }
            }
            if ($v['type'] == 2) {//小区
                $map[] = ['h.village_id', '=', $v['type_id']];
            }
            if ($v['type'] == 3) {//商圈
                $map[] = ['h.business_area_id', '=', $v['type_id']];
            }

            //价格区间
            $map[] = createSectionQuery1($v['price_section'], 'ha.initial_price');

            //面积区间
            $map[] = createSectionQuery1($v['area_section'], 'h.build_area');

            //户型
            if ($v['door_section']) {
                $map[] = createSectionQuery1($v['door_section'], 'h.bedroom');
            }
            $res = db('house')
                ->alias('h')
                ->join('erp_house_auction ha', 'h.auction_id = ha.id', 'LEFT')
                ->where($map)
                ->column('h.id');
            $merge = array_merge($merge, $res);
        }
        //没找到匹配房源
        if (empty($merge)) {
            return [
                'registration_id' => $registration_id,
                'data'            => [],
                'agent_id'        => $agentId
            ];
        }
        return [
            'registration_id' => $registration_id,
            'data'            => array_unique($merge),
            'agent_id'        => $agentId
        ];
    }

}
